package com.xhwl.data.aop;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xhwl.common.enums.OperationTypeEnum;
import com.xhwl.common.enums.OrganizationTypeEnum;
import com.xhwl.common.exception.DataException;
import com.xhwl.common.pojo.cent.sdata.SpaceFunctionType;
import com.xhwl.data.pojo.annotation.SpaceFunctionTypeHandle;
import com.xhwl.data.service.ISpaceFunctionTypeService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author yf
 * @Description:
 * @Date Create in 14:52 2022/06/16
 */
@Component
@Aspect
@Slf4j
public class SpaceFunctionTypeAspect {
    @Autowired
    private ISpaceFunctionTypeService spaceFunctionTypeService;

    @Pointcut("@annotation(spaceFunctionTypeHandle)")
    public void pointcut(SpaceFunctionTypeHandle spaceFunctionTypeHandle) {
    }

    @Before("pointcut(spaceFunctionTypeHandle)")
    public void before(JoinPoint joinPoint, SpaceFunctionTypeHandle spaceFunctionTypeHandle) throws Throwable {
        if (OperationTypeEnum.CREATE.equals(spaceFunctionTypeHandle.operationType()) ||
                OperationTypeEnum.UPDATE.equals(spaceFunctionTypeHandle.operationType())) {
            OrganizationTypeEnum organizationType = spaceFunctionTypeHandle.organizationTypeEnum();
            Short orgTypeId = organizationType.getId();
            Object[] args = joinPoint.getArgs();
            for (Object arg : args) {
                String s = JSONObject.toJSONString(arg);
                JSONObject jsonObject = JSONObject.parseObject(s);
                Integer functionTypeId = jsonObject.getInteger("functionType");
                SpaceFunctionType spaceFunctionType = spaceFunctionTypeService.getOne(new QueryWrapper<SpaceFunctionType>()
                        .eq("id", functionTypeId)
                        .eq("org_type_id", orgTypeId));
                if (null == spaceFunctionType) {
                    log.error("功能类型不存在");
                    throw new DataException("功能类型不存在");
                }
            }
        }
    }
}
